package com.blb.day2;

/**
 * 懒汉式单例模式
 */
public class Singleton5 {

    //volatile 提高线程可见性
    private static volatile Singleton5 instance = null;

    private Singleton5(){
        System.out.println("创建了一个对象");
    }

    public static Singleton5 getInstance(){
        //外层if判断instance不为空，就不执行同步块，用于提升性能
        if(instance == null) {
            synchronized (Singleton5.class) {
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //内层if判断instance为空，就创建单例对象，if和创建对象必须是原子性的
                if (instance == null) {
                    instance = new Singleton5();
                }
            }
        }
        return instance;
    }
}
